package org.sample.thread;

/** 线程互斥 */
public class ThreadMutex {

    public static void main(String[] args) {
        final Business b = new Business();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                b.add(5);
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                b.add(5);
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                b.sub(2);
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                b.sub(2);
            }
        }).start();
    }
}

class Business {

    private int i = 0;

    public synchronized void add(int count) {
        if (i > 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        i++;
        System.out.println(Thread.currentThread().getName() + " add i=" + i);
        this.notify();
    }

    public synchronized void sub(int count) {
        if (i < 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        i--;
        System.out.println(Thread.currentThread().getName() + " sub i=" + i);
        this.notify();
    }
}